package com.mindskip.gushuang.configuration.Job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.mindskip.gushuang.domain.*;
import com.mindskip.gushuang.domain.enums.ExamPaperAnswerStatusEnum;
import com.mindskip.gushuang.repository.*;
import com.mindskip.gushuang.service.*;
import com.mindskip.gushuang.utility.JsonUtil;
import com.mindskip.gushuang.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.gushuang.viewmodel.student.exam.ExamPaperSubmitVM;
import com.mindskip.gushuang.viewmodel.student.exampaper.ExamPaperAnswerPageVM;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {


    @Resource
    private UserService userService;

    @Resource
    private AnsweritemMapper answeritemMapper;


    @Resource
    private ExamPaperSubmissionMapper examPaperSubmissionMapper;

    @Resource
    private ExamPaperAnswerService examPaperAnswerService;


    @Resource
    private TasksService tasksService;


    @Resource
    private QuestionService questionService;


    @Autowired
    private AddressBean addressBean;

    @Resource
    private SubjectService subjectService;

    @Resource
    private SubjectMapper subjectMapper;


    @Scheduled(fixedRate = 100 * 2000)
    @Transactional
    public void configureTasks() throws IOException {
        System.out.println("11111111");
        one();
        two();
    }

    /**
     * 插入   ExamPaperSubmitVM   和   Answeritem
     */

    public void one() {
        QueryWrapper<Tasks> tasksQueryWrapper = new QueryWrapper<>();
        tasksQueryWrapper.eq("isDelete", 0);
        long count = tasksService.count(tasksQueryWrapper);
        if (count == 0) {
            List<User> users = userService.getUsers();
            for (User user : users) {
                ExamPaperAnswerPageVM model = new ExamPaperAnswerPageVM();
                model.setCreateUser(user.getId());
                model.setPageIndex(1);
                model.setPageSize(1000);
                PageInfo<ExamPaperAnswer> examPaperAnswerPageInfo = examPaperAnswerService.studentPage(model);
                List<ExamPaperAnswer> list = examPaperAnswerPageInfo.getList();
                for (ExamPaperAnswer examPaperAnswer : list) {
                    ExamPaperSubmitVM examPaperSubmitVM = new ExamPaperSubmitVM();
                    if (examPaperAnswer.getStatus().equals(ExamPaperAnswerStatusEnum.WaitJudge.getCode())) {
                        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
                        ExamPaperSubmission examPaperSubmission = new ExamPaperSubmission();
                        examPaperSubmission.setExamPaperId(answer.getId());
                        examPaperSubmission.setDoTime(answer.getDoTime());
                        examPaperSubmission.setScore(answer.getScore());
                        ArrayList<Integer> idList = new ArrayList<>();
                        ArrayList<Answeritem> answeritems = new ArrayList<>();
                        for (ExamPaperSubmitItemVM answerItem : answer.getAnswerItems()) {
                            if (answerItem.getDoRight() == null) {
                                Answeritem saveAnswerItem = new Answeritem();
                                saveAnswerItem.setAnsweritemId(answerItem.getId());
                                saveAnswerItem.setScore(answerItem.getScore());
                                saveAnswerItem.setItemOrder(answerItem.getItemOrder());
                                saveAnswerItem.setQuestionId(answerItem.getQuestionId());
                                if (answerItem.getDoRight() != null) {
                                    saveAnswerItem.setDoRight(answerItem.getDoRight().equals(Boolean.TRUE) ? 1 : 0);
                                }
                                //saveAnswerItem.setDoRight(answerItem.getDoRight() != null && answerItem.getDoRight().equals(Boolean.TRUE) ? 1 : 0);
                                saveAnswerItem.setContent(answerItem.getContent());
                                saveAnswerItem.setContentArray(JsonUtil.toJsonStr(answerItem.getContentArray()));
                                saveAnswerItem.setQuestionScore(answerItem.getQuestionScore());
                                int saveAnswerItemId = answeritemMapper.insert(saveAnswerItem);
                                idList.add(saveAnswerItem.getId());
                            }
                        }
                        examPaperSubmission.setAnsweritems(JsonUtil.toJsonStr(idList));
                        examPaperSubmission.setJudearr(JsonUtil.toJsonStr(idList));
                        examPaperSubmissionMapper.insert(examPaperSubmission);
                    }
                }
            }
        }
    }


    @SneakyThrows
    public void two() throws IOException {
        QueryWrapper<ExamPaperSubmission> queryWrapper = new QueryWrapper<>();
        // 使用selectList方法查询所有数据
        queryWrapper.eq("isJude", 0); // 没判过
        List<ExamPaperSubmission> examPaperSubmissions = examPaperSubmissionMapper.selectList(queryWrapper);
        ArrayList<ExamPaperSubmitVM> examPaperSubmitVMs = new ArrayList<>();
        for (ExamPaperSubmission examPaperSubmission : examPaperSubmissions) {
            ExamPaperSubmitVM examPaperSubmitVM = new ExamPaperSubmitVM();
            examPaperSubmitVM.setId(examPaperSubmission.getExamPaperId());
            examPaperSubmitVM.setDoTime(examPaperSubmission.getDoTime());
            examPaperSubmitVM.setScore(examPaperSubmission.getScore());
            List<Integer> ids = JsonUtil.toJsonListObject(examPaperSubmission.getAnsweritems(), Integer.class);
            QueryWrapper<Answeritem> answeritemQueryWrapper = new QueryWrapper<>();
            answeritemQueryWrapper.in("id", ids);
            List<Answeritem> answeritemList = answeritemMapper.selectList(answeritemQueryWrapper);
            ArrayList<ExamPaperSubmitItemVM> examPaperSubmitItemVMs = new ArrayList<>();
            for (Answeritem answeritem : answeritemList) {
                ExamPaperSubmitItemVM examPaperSubmitItemVM = new ExamPaperSubmitItemVM();
                examPaperSubmitItemVM.setId(answeritem.getAnsweritemId());
                examPaperSubmitItemVM.setQuestionId(answeritem.getQuestionId());
                if (answeritem.getDoRight() != null) {
                    examPaperSubmitItemVM.setDoRight(answeritem.getDoRight().equals(1) ? Boolean.TRUE : Boolean.FALSE);
                }
                examPaperSubmitItemVM.setContent(answeritem.getContent());
                examPaperSubmitItemVM.setItemOrder(answeritem.getItemOrder());
                examPaperSubmitItemVM.setContentArray(JsonUtil.toJsonListObject(answeritem.getContentArray(), String.class));
                examPaperSubmitItemVM.setScore(answeritem.getScore());
                examPaperSubmitItemVM.setQuestionScore(answeritem.getQuestionScore());
                Integer id = examPaperSubmitItemVM.getId();
                Integer questionId = examPaperSubmitItemVM.getQuestionId();
                Question question = questionService.selectById(questionId);
                Tasks tasks = new Tasks();
                Integer subjectId = question.getSubjectId();
                Subject subject = subjectMapper.selectByPrimaryKey(subjectId);
                tasks.setSubjectname(subject.getName());
                tasks.setStandardanswer(question.getCorrect());
                tasks.setScore(Integer.valueOf(question.getScore()));
                String imgUrl = tasks.getImgurl();
                if (!question.getQuestionType().equals(5)) {
                    continue;
                }
                com.mindskip.gushuang.domain.content content1 = JsonUtil.toJsonObject(examPaperSubmitItemVM.getContent(), com.mindskip.gushuang.domain.content.class);
                tasks.setImgurl(JsonUtil.toJsonStr(content1.getImgUrls()));
                String s = JsonUtil.toJsonStr(content1.getHtml());
                Document doc = Jsoup.parse(s);
                String text = doc.text();
                System.out.println(text);
                tasks.setAnswertext(text);

                System.out.println(tasks.getImgurl());
                System.out.println(tasks.getSubjectname());
                System.out.println(tasks.getGradingstandard());
                tasks.setStandardanswer(Jsoup.parse(tasks.getStandardanswer()).text());
                System.out.println(tasks.getStandardanswer());
                System.out.println(tasks.getScore().toString());
                System.out.println(tasks.getAnswertext());
                // 创建HttpClient实例
                CloseableHttpClient httpClient = HttpClients.createDefault();
                // 创建HttpPost实例
                HttpPost httpPost = new HttpPost(addressBean.getAddress()); // 替换为你的URL
                // 创建参数列表并转换为JSON对象
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("imgUrl", tasks.getImgurl());
                jsonBody.put("subjectName", tasks.getSubjectname());
                if (tasks.getGradingstandard() == null) {
                    jsonBody.put("gradingStandard", "1");
                } else {
                    jsonBody.put("gradingStandard", tasks.getGradingstandard());
                }
                jsonBody.put("standardAnswer", tasks.getStandardanswer());
                jsonBody.put("score", tasks.getScore().toString());
                jsonBody.put("answerText", tasks.getAnswertext());
                jsonBody.put("category", "1");
                // 将JSON对象设置为请求实体
                StringEntity entity = new StringEntity(jsonBody.toString(), "UTF-8");
                httpPost.setEntity(entity);
                // 设置请求的内容类型为application/json
                httpPost.setHeader("Content-Type", "application/json");
                // 执行请求
                HttpResponse response = httpClient.execute(httpPost);
                // 获取响应内容
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(result);

                try {
                    JSONArray jsonArray = JSONArray.parseArray(result);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String score = jsonObject.getString("score");
                    answeritem.setScore(score);
                    answeritem.setIsjude(1);
                    int i = answeritemMapper.updateById(answeritem);
                    examPaperSubmitItemVM.setScore(score);
                    String cause_of_error = jsonObject.getString("Cause of error");
                    examPaperSubmitItemVM.setEvaluate(cause_of_error);
                } catch (Exception e) {
                    e.printStackTrace();
                    answeritem.setScore("0");
                    answeritem.setIsjude(1);
                    examPaperSubmitItemVM.setScore("0");
                    examPaperSubmitItemVM.setEvaluate("批改错误");
                }
                examPaperSubmitItemVMs.add(examPaperSubmitItemVM);
            }
            examPaperSubmission.setIsjude(1);
            int i = examPaperSubmissionMapper.updateById(examPaperSubmission);
            examPaperSubmitVM.setAnswerItems(examPaperSubmitItemVMs);
            examPaperSubmitVMs.add(examPaperSubmitVM);
        }
        for (ExamPaperSubmitVM examPaperSubmitVM : examPaperSubmitVMs) {
            examPaperAnswerService.judge(examPaperSubmitVM);
        }
    }
}